package mail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;

import contacts.Owner;

/**
 * Testklasse
 * 
 * @author Michi
 * 
 */
public class TestMailtoDB {

	public static void main(String[] args) throws Exception {

		Owner test = new Owner("Michael", "Brandt");
		test.setEmail("testmail@brotek.eu");
		test.setImapServer("imap.brotek.eu");
		test.setMailPass("test123");
		test.setSmtpServer("smtp.brotek.eu");
		test.setProvider("imap");

		Owner test1 = new Owner("Michael", "Brandt");
		test1.setEmail("testmailsopra@gmail.com");
		test1.setImapServer("imap.gmail.com");
		test1.setMailPass("sopra1213");
		test1.setSmtpServer("smtp.brotek.eu");
		test1.setProvider("imaps");

		MyModelEmail mme = new MyModelEmail();
		// LinkedList testList = mme.listInbox(test);

		LinkedList<Mail> testList = mme.listInbox();

		System.out.println(testList.size());
		mme.deleteMail(testList.get(10));
		System.out.println(testList.size());

		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
		Statement stat = conn.createStatement();
		// stat.executeUpdate("drop table if exists mail;");
		stat.executeUpdate("create table if not exists mail (adress, text, hash);");
		PreparedStatement prep = conn
				.prepareStatement("insert into mail values (?, ?,?);");

		ResultSet hashresult = stat.executeQuery("select hash from mail;");

		while (hashresult.next()) {
			for (int i = 0; i < testList.size();) {
				if (testList.get(i).getHash() == hashresult.getLong(1)) {
					testList.remove(i);
					System.out.println("removed");

				} else
					i++;
			}
		}

		for (int i = 0; i < testList.size(); i++) {
			prep.setString(1, testList.get(i).getFrom());
			prep.setString(2, testList.get(i).getText());
			prep.setLong(3, testList.get(i).getHash());
			prep.addBatch();
		}

		conn.setAutoCommit(false);
		prep.executeBatch();
		conn.setAutoCommit(true);

		ResultSet rs = stat.executeQuery("select * from mail;");
		int b = 0;
		while (rs.next()) {
			System.out.println("name = " + rs.getString("adress"));
			System.out.println("text = " + rs.getString("text"));
			System.out.println("hash = " + rs.getString("hash"));
			b++;
			System.out.println(b);
		}
		rs.close();
		conn.close();
	}
}
